<?php

header ('Content-type:text/html;charset=utf8');

class Token
{
    private static $salt = '6Zi/5aOr5aSn5aSr5pKS5pem5Y+R6YCB5Yiw5Y+R6YCB5Yiw5Y+R6YCB5Yiw5qK16JKC5YaI55qE6K+05rOV55S15pS+6LS5';
    public static function get_token($id, $expire){
        $msg = <<<msg
        {
            "id": "$id",
            "expire": "$expire"
        }
        msg;
        $token_head = base64_encode($msg);
        $tmp = substr_replace($token_head, self::$salt, 10, 0);
        $token = $token_head . '.' . hash('sha256', $tmp);
        return $token;
    }
    /*
    * param: str $token
    * return: {
        "id" => "userid",
        "expire" => "time"
    }
    */
    public static function resolve_token($token){
        $token_arr = explode('.', $token);
        $token_head = $token_arr[0];
        // 验证token失败
        if ($token_arr[1] != hash('sha256', substr_replace($token_head, self::$salt, 10, 0))) return false;

        // 验证成功返回包含用户ID和token过期时间的对象
        $msg = json_decode(base64_decode($token_head));
        return $msg;
    }
}



